package sz.szsmk.citizencard.model.network;

import android.app.Activity;
import android.widget.Toast;

import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.dialog.LoadingDialog;

import rx.Subscriber;
/**
 * des:订阅封装
 * Created by qiuling
 * on 2017/08/12
 */

/********************使用例子********************/
/*_apiService.login(mobile, verifyCode)
        .//省略
        .subscribe(new RxSubscribers<User user>(mContext,false) {
@Override
public void _onNext(User user) {
        // 处理user
        }

@Override
public void _onError(String msg) {
        ToastUtil.showShort(mActivity, msg);
        });*/
public abstract class RxSubscribers<T> extends Subscriber<T> {

    /**
     * 网络类型没有网络类型
     */
    public static final String NETWORK_NOTCONNECT = "未连接网络";
    /**
     * 服务器异常
     */
    public static final String SERVICE_NOT_REFULT = "服务器异常";
    private boolean isShowDialog = false;
    private Activity activity;

    @Override
    public void onCompleted() {

    }

    public RxSubscribers(boolean isShowDialog, Activity activity) {
        this.isShowDialog = isShowDialog;
        this.activity = activity;
    }
    public RxSubscribers(){

    }

    @Override
    public void onStart() {
        super.onStart();
        if (isShowDialog) {
            startLoadingDialog();
        }

    }


    @Override
    public void onNext(T t) {
        _onNext(t);
        if (isShowDialog) {
            stopLoadingDialog();
        }
    }

    @Override
    public void onError(Throwable e) {
        if (isShowDialog) {
            stopLoadingDialog();
        }
        e.printStackTrace();
        //网络
        if (!NetWorkUtils.isNetConnected(DaggerApplication.getIns())) {
            _onError(NETWORK_NOTCONNECT);
        }
        //服务器
        else if (e instanceof ServerExceptions) {
            _onError(e.getMessage());
        }
        //其它
        else {
            _onError(e.getMessage());
        }
    }

    /**
     * 开启浮动加载条
     *
     * @param @null
     * @return
     */
    protected void startLoadingDialog() {
        Toast.makeText(activity, "正在加载", Toast.LENGTH_SHORT).show();
        //开启对话框默认提示
        //LoadingDialog.showDialogForLoading(activity);
    }

    /**
     * 关闭浮动进度条dialog
     *
     * @param @null
     * @return
     */
    protected void stopLoadingDialog() {
    }

    protected abstract void _onNext(T t);

    protected abstract void _onError(String message);

}
